package com.ark.security.service;

import com.ark.common.domain.entity.sys.SysUser;
import com.ark.common.domain.model.LoginUser;
import com.ark.common.exception.ServiceException;
import com.ark.service.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService userService;
    @Resource
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user= userService.selectUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("用户名或密码错误");
        }else if (user.getDelFlag() == 1) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("用户已被删除");
        }else if (user.getStatus().equals("1")) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("用户已被停用");
        }
        Set<String> menuPermission = permissionService.getMenuPermission(user);
        return new LoginUser(user.getId(),user,menuPermission);
    }


}
